﻿using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using ArchiveRecoveryProgram;

namespace ArchiveRecoveryProgram
{
    public class DirWatcher : IDisposable
    {
        // 设置要监控的文件夹路径
        static string sourceFolderPath = @"C:\ProgramData\PopCap Games\PlantsVsZombies\pvzHE\yourdata";
        // 设置备份文件夹路径
        static string backupFolderPath = @"C:\ProgramData\PopCap Games\PlantsVsZombies\pvzHE\yourdata_Backup";

        private static FileSystemWatcher watcher;

        InteractiveForm interactiveForm;

        public delegate void ThreadDispose();
        public ThreadDispose disposeDelegate;

        public bool isWatching;

        public DirWatcher(InteractiveForm myForm)
        {
            interactiveForm = myForm;
            disposeDelegate = new ThreadDispose(Dispose);
        }

        public void Run()
        {
            watcher = new FileSystemWatcher();
            watcher.Path = sourceFolderPath;
            watcher.Filter = "*.*"; // 监控所有文件
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.IncludeSubdirectories = false; // 是否包含子目录

            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            // watcher.Deleted += new FileSystemEventHandler(OnDeleted);

            // 启动监控
            watcher.EnableRaisingEvents = true;
            isWatching = true;
            logInfo("开始监听存档文件变化");

            while (true)
            {

            }
        }

        private void logInfo(String str)
        {
            DateTime currentTime = DateTime.Now;
            string formattedTime = currentTime.ToString("yyyy-MM-dd HH:mm:ss");
            string logMessage = formattedTime + ":" + str + Environment.NewLine;

            interactiveForm.dirWatcherDelegate(logMessage);
        }

        // 文件发生变化时的事件处理程序
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            // 执行备份操作
            bool res = BackupFile(e.FullPath);
            string fileName = Path.GetFileName(e.FullPath);
            if (res)
                logInfo(fileName + "已备份");
            else
                logInfo(fileName + "备份失败");
            // 处理文件或目录变化的代码
        }

        // 文件发生变化时的事件处理程序
        private static void OnDeleted(object source, FileSystemEventArgs e)
        {
            // 执行备份操作
            // DeleteBackupedFile(e.FullPath);
        }

        // 初始化函数，删除备份文件夹下的所有文件，并将源文件夹下的所有文件复制到备份文件夹
        public static bool Init()
        {
            try
            {
                // 检查备份文件夹是否存在
                if (!Directory.Exists(backupFolderPath))
                {
                    // 获取备份文件夹中的所有文件
                    string[] backupFiles = Directory.GetFiles(backupFolderPath);

                    // 删除备份文件夹中的所有文件
                    foreach (string backupFile in backupFiles)
                    {
                        File.Delete(backupFile);
                    }
                }
                else
                {
                    // 如果备份文件夹不存在，创建它
                    Directory.CreateDirectory(backupFolderPath);
                }

                // 获取源文件夹中的所有文件
                string[] sourceFiles = Directory.GetFiles(sourceFolderPath);

                // 遍历源文件夹中的每个文件，并将其复制到备份文件夹
                foreach (string sourceFile in sourceFiles)
                {
                    // 从源文件的路径获取文件名
                    string fileName = Path.GetFileName(sourceFile);
                    // 构建备份文件的完整路径
                    string backupFilePath = Path.Combine(backupFolderPath, fileName);

                    // 复制文件到备份文件夹
                    File.Copy(sourceFile, backupFilePath, true);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }


        // 备份文件的方法
        public static bool BackupFile(string filePath)
        {
            try
            {
                string fileName = Path.GetFileName(filePath);
                string backupFilePath = Path.Combine(backupFolderPath, fileName);
                // 复制文件到备份文件夹
                File.Copy(filePath, backupFilePath, true);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        // 当源文件存档被删除时，也删除备份存档的文件
        /*
        public static void DeleteBackupedFile(string filePath)
        {
            try
            {
                // 从filePath获取文件名
                string fileName = Path.GetFileName(filePath);
                // 构建备份文件的完整路径
                string backupFilePath = Path.Combine(backupFolderPath, fileName);

                // 检查备份文件是否存在
                if (File.Exists(backupFilePath))
                {
                    // 删除备份文件
                    File.Delete(backupFilePath);
                   
                }
                else
                {
                   
                }
            }
            catch (Exception ex)
            {
                
            }
        }
        */

        // 用备份存档的文件覆盖原文件夹同名文件，如果原文件夹不存在该文件，则新建同名文件
        public static bool OverWriteSourceFiles()
        {
            if(watcher != null)
                watcher.EnableRaisingEvents = false;
            try
            {
                // 获取备份文件夹中的所有文件
                string[] backupFiles = Directory.GetFiles(backupFolderPath);
                foreach (string backupFile in backupFiles)
                {
                    // 从备份文件的路径获取文件名
                    string fileName = Path.GetFileName(backupFile);
                    // 构建源文件夹中文件的完整路径
                    string sourceFilePath = Path.Combine(sourceFolderPath, fileName);

                    // 检查源文件夹中是否存在同名文件
                    if (File.Exists(sourceFilePath))
                    {
                        // 用备份文件覆盖源文件夹中的文件
                        File.Copy(backupFile, sourceFilePath, true);
                    }
                    else
                    {
                        // 如果源文件夹中不存在该文件，则新建同名文件
                        File.Copy(backupFile, sourceFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                if (watcher != null)
                    watcher.EnableRaisingEvents = true;
                return false;
            }
            if (watcher != null)
                watcher.EnableRaisingEvents = true;
            return true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (isWatching)
                {
                    watcher.EnableRaisingEvents = false;
                    watcher.Dispose();
                    isWatching = false;
                }
            }
        }

        ~DirWatcher()
        {
            Dispose(false);
        }
    }
}
